package com.greenhouse.controller;

import com.greenhouse.config.Request;
import com.greenhouse.model.User;
import com.greenhouse.request.UserLoginRequest;
import com.greenhouse.service.UserService;
import com.greenhouse.utily.SessionUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    private static final String AVATAR_URL = "E:/develop/file/wechat/img/";
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Request<User> login(@RequestBody UserLoginRequest request,HttpServletRequest  servletRequest) {
        User user = userService.login(request.getUsername(), request.getPassword());
        if (user!= null) {
            SessionUtils.setSessionUser(servletRequest, user);
            return Request.success("登录成功", user);
        }
        return Request.error("用户名或密码错误", null);
    }


    /**
     * 传递用户头像
     */
    @GetMapping("/getHeadPortrait")
    public ResponseEntity<byte[]> getHeadPortrait(HttpServletRequest request) {
        User user = SessionUtils.getSessionUser(request);
        if (user == null) {
            return ResponseEntity.status(404).build();
        }
        String imagePath = user.getHeadImgUrl();
        System.out.println(imagePath);
        try {
            if (imagePath == null || imagePath.isEmpty()) {
                imagePath = "default_avatar.png";
            }
            File imageFile = new File(AVATAR_URL + File.separator + imagePath);
            byte[] bytes = Files.readAllBytes(imageFile.toPath());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
    /**
     * 修改上传用户头像
     *
     */
    @PostMapping("/updateHeadPortrait")
    public Request<String> updateHeadPortrait(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        User user = SessionUtils.getSessionUser(request);
        if (user == null) {
            return Request.error("请先登录", null);
        }
        if (file == null || file.isEmpty()) {
            return Request.error("请选择上传头像", null);
        }
        //删除原有头像
        String oldHeadImgUrl = user.getHeadImgUrl();
        if (oldHeadImgUrl != null && !oldHeadImgUrl.isEmpty()) {
            File oldFile = new File(AVATAR_URL + File.separator + oldHeadImgUrl);
            if (oldFile.exists()) {
                oldFile.delete();
            }
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = "head_" + user.getId() + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(fileName);
        try {
            file.transferTo(new File(AVATAR_URL + File.separator + fileName));
            Integer n = userService.updateHeadImg(fileName, user.getId());
            if (n == 1) {
                //更新Session
                user.setHeadImgUrl(fileName);
                SessionUtils.setSessionUser(request, user);
                return Request.success("上传成功", fileName);
            }
            return Request.error("上传失败", null);
        } catch (IOException e) {
            e.printStackTrace();
            return Request.error("上传失败", null);
        }
    }
    /**
     * 修改用户信息
     */
    @RequestMapping("/update")
    public Request<String> update(HttpServletRequest request, @RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("password")String password) {
        User user = SessionUtils.getSessionUser(request);
        if (user == null) {
            return Request.error("请先登录", null);
        }
        Integer n = null;
        if (password!= null &&!password.isEmpty()) {
            n = userService.updatePassword(password, user.getId());
        }
        if (name!= null &&!name.isEmpty()) {
            n = userService.updateName(name, user.getId());
        }
        if (email!= null &&!email.isEmpty()) {
            n = userService.updateEmail(email, user.getId());
        }
        if (n == 1) {
            user.setName(name);
            user.setEmail(email);
            SessionUtils.setSessionUser(request, user);
            return Request.success("修改成功", null);
        }
        return Request.error("修改失败", null);
    }
    /**
     * 注销账户
     */
    @GetMapping("/delete")
    public Request<String> delete(HttpServletRequest request) {
        User user = SessionUtils.getSessionUser(request);
        if (user == null) {
            return Request.error("请先登录", null);
        }
        Integer n = userService.deleteUser(user.getId());
        System.out.println(n);
        if (n == 1) {
            //注销Session
            SessionUtils.setSessionUser(request, null);
            return Request.success("注销成功", null);
        }
        return Request.error("注销失败", null);
    }
    /**
     * 管理员添加用户
     * @param request
     * @return
     */
    @PostMapping("/addUser")
    public Request<String> addUser(HttpServletRequest request) {
        if (!SessionUtils.isAdminUser(request)) {
            return Request.error("权限不足", null);
        }
        System.out.println("添加账户");
        User newUser = userService.insertUser();
        if (newUser != null) {
            return Request.success("添加成功", newUser.getUsername());
        }
        return Request.error("添加失败", null);
    }
}